﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Facade;
using IronOne.SalesOne.BusinessObjects;
using System.Configuration;


namespace IronOne.SalesOne.SalesOneWeb.Collection
{
    public partial class SearchVerifyCollectionTransaction : SOSecurityPage,IDataPage, IntTest
    {
        StructureFacade facade;
        int userType;
        private static int pageNo = 1;

        public List<Branch> brnch;
        public List<SalesOneUnit> un;
        public List<string> so;

        protected void Page_Load(object sender, EventArgs e)
        {
            facade = new StructureFacade();
            
            if (!Page.IsPostBack)
            {
                if (Session["CSSNo"]!= null)
                {
                    Session.Remove("CSSNo");

                }
                
                pageNo = 1;
                ValidateUserCredentials(Request.Url.LocalPath);

                User user = facade.GetUser(User.Identity.Name);
                //User user = facade.GetUser("ss");
                UserInformation info = facade.GetUserInformation(User.Identity.Name);
                userType = info.UserType;
                ViewState["UserType"] = userType;
                bool flag = false;

                if (userType == 4)
                {
                    /*if (user.SoCode != null)
                    {
                        ddlSO.Items.Add(user.SoCode);
                        ddlSO.SelectedIndex = ddlSO.Items.Count - 1;

                        ddlSO.Enabled = false;
                    }
                    else*/
                    populateSOCodes(facade.GetSOsInUnit(user.NodeId));
                    flag = true;
                }

                if (flag == true)
                {
                    ddlUnitCode.Items.Clear();
                    ListItem item = new ListItem(info.UnitName,info.UnitId.ToString());
                    //ddlUnitCode.DataTextField = "UnitName";
                    //ddlUnitCode.DataValueField = "UnitId";
                    ddlUnitCode.Items.Add(item);
                    ddlUnitCode.SelectedIndex = ddlUnitCode.Items.Count - 1;

                    ddlUnitCode.Enabled = false;
                }
                else if (userType == 3)
                {
                    populateUnits(facade.GetUnitsForBranch(user.NodeId));
                    addDefaultItem(ddlSOCode);
                    flag = true;
                }

                if (flag == true)
                {
                    ddlBranchCode.Items.Clear();
                    ListItem item = new ListItem(info.BranchName, info.BranchId.ToString());
                    //ddlBranchCode.DataValueField = "BranchId";
                    //ddlBranchCode.DataTextField = "BranchName";
                    ddlBranchCode.Items.Add(item);
                    ddlBranchCode.SelectedIndex = ddlBranchCode.Items.Count - 1;

                    ddlBranchCode.Enabled = false;
                }
                else if (userType == 2)
                {
                    populateBranches(facade.GetBranchesForGroup(user.NodeId));
                    addDefaultItem(ddlUnitCode);
                    addDefaultItem(ddlSOCode);
                    flag = true;
                }

                if (userType == 1)
                {
                    populateBranches(facade.GetBranches("BranchName ASC"));
                    addDefaultItem(ddlUnitCode);
                    addDefaultItem(ddlSOCode);
                }

                setControls();
                btnUpdate.Visible = false;
                //btnUpdate.Visible = true;

                if (Request.QueryString["load"] == "true")
                {
                    showUserGrid(Convert.ToInt32(Session["PageNo"]));
                }
            }

            //if (Request.UrlReferrer.ToString().Contains("/Collection/VerifyCollectionTransactionDetails.aspx"))
            

        }

        #region Event Handling methods

        protected void ddlUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlUnitCode.SelectedIndex > 0)
            {
                populateSOCodes(facade.GetSOsInUnit(int.Parse(ddlUnitCode.SelectedValue)));
            }
            setControls();
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            if (Session["CSSNo"] == null || Session["CSSNo"].ToString() == "")
            {
                Session["CSSNo"] = ((GridViewRow)Session["firstRow"]).Cells[2].Text;
                Session["SOCode"] = ((GridViewRow)Session["firstRow"]).Cells[3].Text;
                Session.Remove("firstRow");
            }
            //Session["PageNo"] = pageNo;

            Response.Redirect("~/Collection/VerifyCollectionTransactionDetails.aspx?CSSNo=" + Session["CSSNo"].ToString() + "&SOCode=" + Session["SOCode"].ToString() + "&Status=" + Session["CSSStatus"], false);
            //Response.Redirect("~/Collection/VerifyCollectionTransactionDetails.aspx");
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                pageNo = 1;
                UCGrid1.SetText("1");

                if (ViewState["UserType"] != null && Convert.ToInt32(ViewState["UserType"]) != 1)
                {
                    //Add Search Criterias to Session
                    Session["txtCSSno"] = txtCssno.Text;
                    Session["CSSStatus"] = ddlCssStatus.Text;
                    Session["BranchID"] = ddlBranchCode.SelectedValue;
                    Session["UnitID"] = (ddlUnitCode.SelectedIndex == 0) ? "" : ddlUnitCode.SelectedValue;
                    Session["SOcd"] = (ddlSOCode.SelectedIndex == 0) ? "" : ddlSOCode.SelectedItem.Text;
                    Session["PageNo"] = pageNo;

                    btnUpdate.Visible = true;
                    showUserGrid(pageNo);
                }
                else
                {
                    if (ddlBranchCode.SelectedIndex > 0)
                    {
                        //Add Search Criterias to Session
                        Session["txtCSSno"] = txtCssno.Text;
                        Session["CSSStatus"] = ddlCssStatus.Text;
                        Session["BranchID"] = ddlBranchCode.SelectedValue;
                        Session["UnitID"] = (ddlUnitCode.SelectedIndex == 0) ? "" : ddlUnitCode.SelectedValue;
                        Session["SOcd"] = (ddlSOCode.SelectedIndex == 0) ? "" : ddlSOCode.SelectedItem.Text;
                        Session["PageNo"] = pageNo;

                        btnUpdate.Visible = true;
                        showUserGrid(pageNo);
                    }
                    else
                    {
                        btnUpdate.Visible = false;
                        UCGrid1.Visible = false;
                        MassageSummery("IIS537");
                    }
                }
            }
            catch (Exception)
            {
                
            }

            

            
        }

        #endregion

        public void showUserGrid(int pageNo)
        {
            if (Session["txtCSSno"] != null)
            {
                string cssNo = Session["txtCSSno"].ToString();
                string cssStatus = Session["CSSStatus"].ToString();
                int branchID = Convert.ToInt32(Session["BranchID"]);
                string unitCD = Session["UnitID"].ToString();
                string soCD = Session["SOcd"].ToString();
                int pageNum = pageNo;//Convert.ToInt32(Session["PageNo"]);

                FinanceFacade fac = new FinanceFacade();
                //List<CollectionTransaction> collectionList = fac.GetCollectionTransactions(txtCssno.Text,
                //                                                                           ddlCssStatus.SelectedItem.Text,
                //                                                                           Convert.ToInt32(ddlBranchCode.SelectedValue),
                //                                                                           (ddlUnitCode.SelectedIndex == 0) ? "" : ddlUnitCode.SelectedValue,
                //                                                                           (ddlSOCode.SelectedIndex == 0)?"":ddlSOCode.SelectedItem.Text,"",pageNo);
                List<CollectionTransaction> collectionList = fac.GetCollectionTransactions(cssNo,
                                                                                           cssStatus,
                                                                                           branchID,
                                                                                           unitCD,
                                                                                           soCD,
                                                                                           "", pageNum);

                if (collectionList.Count == Convert.ToInt32(ConfigurationManager.AppSettings["GridCount"]))
                {
                    UCGrid1.IsLastPage = (fac.GetCollectionTransactions(cssNo,
                                                                       cssStatus,
                                                                       branchID,
                                                                       unitCD,
                                                                       soCD,
                                                                       "", pageNum + 1)).Count > 0 ? false : true;
                }

                int[] hideIndex = { 1, 4, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45 };
                if (collectionList != null && collectionList.Count > 0)
                {
                    //Set GridView Style
                    UCGrid1.styleList = new List<GridViewStyle> {

                new GridViewStyle{
                    ColumnId = "CSSNo",
                    ColumnHeader = "CSS No",
                    ColumnWidth = 150},
                new GridViewStyle{
                    ColumnId = "SOCode",
                    ColumnHeader = "SO Code",
                    ColumnWidth = 150},
                new GridViewStyle{
                    ColumnId = "Status",
                    ColumnHeader = "Status",
                    ColumnWidth = 150},
                new GridViewStyle{
                    ColumnId = "CollectionAmount",
                    ColumnHeader = "Collection Amount(Rs)",
                    ColumnWidth = 150},
                new GridViewStyle{
                    ColumnId = "LastSyncDate",
                    ColumnHeader = "Last Sync Date",
                    ColumnWidth = 150},
                    };

                    UCGrid1.SetDataSource(collectionList, hideIndex);
                    UCGrid1.DataBind();
                    UCGrid1.Visible = true;
                    btnUpdate.Visible = true;
                }
                else
                {
                    btnUpdate.Visible = false;
                    UCGrid1.Visible = false;
                    MassageSummery("IIS504");
                }
            }
        }

        private void setControls()
        {
            /*if (ddlBranch.SelectedIndex == 0)
            {
                ddlUnit.Enabled = false;
                ddlUnit.SelectedIndex = 0;
            }
            else
            {
                ddlUnit.Enabled = true;
            }

            if (ddlUnit.SelectedIndex <= 0)
            {
                ddlSO.Enabled = false;
                ddlSO.SelectedIndex = 0;
            }
            else
            {
                ddlSO.Enabled = true;
            }

            if (ddlSO.SelectedIndex <= 0)
            {
                btnSearch.Enabled = false;
            }
            else
            {
                btnSearch.Enabled = true;
            }*/



            /*if ((userType == 2 || userType == 1) && ddlBranch.SelectedIndex == 0)
            {
                ddlUnit.Enabled = false;
                ddlUnit.SelectedIndex = 0;
            }
            else
            {
                ddlUnit.Enabled = true;
            }

            if (userType == 3 && ddlUnit.SelectedIndex <= 0)
            {
                ddlSO.Enabled = false;
                ddlSO.SelectedIndex = 0;
            }
            else
            {
                ddlSO.Enabled = true;
            }

            if (userType == 4 && ddlSO.SelectedIndex <= 0)
            {
                btnSearch.Enabled = false;
            }
            else
            {
                btnSearch.Enabled = true;
            }*/
            /*
            if (ddlSO.SelectedIndex <= 0)
                btnSearch.Enabled = false;
             * */
        }

        private void populateBranches(List<Branch> branches)
        {
            ddlBranchCode.DataSource = branches;
            ddlBranchCode.DataTextField = "BranchName";
            ddlBranchCode.DataValueField = "BranchID";
            ddlBranchCode.DataBind();

            addDefaultItem(ddlBranchCode);
        }

        private void populateUnits(List<SalesOneUnit> units)
        {
            ddlUnitCode.DataSource = units;
            ddlUnitCode.DataTextField = "Name";
            ddlUnitCode.DataValueField = "UnitID";
            ddlUnitCode.DataBind();

            addDefaultItem(ddlUnitCode);
        }

        private void populateSOCodes(List<string> users)
        {
            ddlSOCode.Items.Clear();
            foreach (string str in users)
            {
                ddlSOCode.Items.Add(str);
            }
            addDefaultItem(ddlSOCode);
        }

        private void addDefaultItem(DropDownList ddl)
        {
            ListItem newItem = new ListItem("Select...","0");
            ddl.Items.Insert(0, newItem);
        }

        public void Search(int page, string sortExpression)
        {
           
        }

        #region IIntTest Members


        //public void Next()
        //{
        //    try
        //    {
        //        if (UCGrid1.GetText() != "1")
        //        {
        //            pageNo = Convert.ToInt32(UCGrid1.GetText()) + 1;
        //            UCGrid1.SetText(pageNo.ToString());

        //        }
        //        else
        //        {
        //            pageNo = 2;
        //            UCGrid1.SetText("2");

        //        }

        //        Search(pageNo, "MessageId ASC");
        //    }
        //    catch { MassageSummery("IIS514"); }
        //}

        //public void Previous()
        //{
        //    try
        //    {
        //        if (UCGrid1.GetText() != "1")
        //        {
        //            pageNo = Convert.ToInt32(UCGrid1.GetText()) - 1;
        //            UCGrid1.SetText(pageNo.ToString());

        //            Search(pageNo, "MessageId ASC");
        //        }
        //    }
        //    catch { MassageSummery("IIS514"); }
        //}

        //public void Go()
        //{
        //    try
        //    {
        //        int p = int.Parse(UCGrid1.GetText());
        //        if (p != 0)
        //        {
        //            try
        //            {
        //                Search(p, "MessageId ASC");
        //                pageNo = p;
        //            }
        //            catch (Exception)
        //            {

        //                throw;
        //            }


        //        }
        //    }
        //    catch { MassageSummery("IIS505"); }

        //}

        #endregion


        #region IntTest Members

        public void Next()
        {
            if (pageNo != 1)
            {
                pageNo = pageNo + 1;
                UCGrid1.SetText(pageNo.ToString());

            }
            else
            {
                pageNo = 2;
                UCGrid1.SetText("2");

            }

            showUserGrid(pageNo);
        }

        public void Previous()
        {
            if (UCGrid1.GetText() != "1")
            {
                pageNo = Convert.ToInt32(UCGrid1.GetText()) - 1;
                UCGrid1.SetText(pageNo.ToString());

                showUserGrid(pageNo);
            }
        }

        public void Go()
        {
            int p = int.Parse(UCGrid1.GetText());
            if (p != 0)
            {
                try
                {
                    showUserGrid(p);
                    pageNo = p;
                }
                catch (Exception)
                {

                    throw;
                }

            }

        }

        #endregion

        #region IDataPage Members

        void IDataPage.Create()
        {
            throw new NotImplementedException();
        }

        void IDataPage.View()
        {
            throw new NotImplementedException();
        }

        void IDataPage.Update()
        {
            throw new NotImplementedException();
        }

        void IDataPage.Delete()
        {
            throw new NotImplementedException();
        }

        void IDataPage.Cancel()
        {
            throw new NotImplementedException();
        }

        void IDataPage.GetId(GridViewRow row)
        {
            Session["CSSNo"] = row.Cells[2].Text;
            Session["SOCode"] = row.Cells[3].Text;
        }

        #endregion

        protected void ddlBranchCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ddlBranchCode.SelectedIndex > 0)
                {
                    ddlUnitCode.Items.Clear();
                    populateUnits(facade.GetUnitsForBranch(Convert.ToInt32(ddlBranchCode.SelectedValue)));
                    so = new List<string>();
                    populateSOCodes(so);
                }
                else
                {
                    List<SalesOneUnit> units = new List<SalesOneUnit>();
                    populateUnits(units);

                    List<string> us = new List<string>();
                    populateSOCodes(us);
                }
            }
            catch (Exception)
            {

            }
            
        }

        protected void ddlUnitCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ddlUnitCode.SelectedIndex > 0)
                {
                    ddlSOCode.Items.Clear();
                    populateSOCodes(facade.GetSOsInUnit(Convert.ToInt32(ddlUnitCode.SelectedValue)));
                }
                else
                {
                    List<string> us = new List<string>();
                    populateSOCodes(us);

                }

            }
            catch (Exception)
            {

            }

            
        }
    }
}
